package com.seal.mchat.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.handler.annotation.MessageExceptionHandler;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.messaging.simp.broker.BrokerAvailabilityEvent;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.util.MimeTypeUtils;

import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;


/**
 * Created by seal on 2016/4/3.
 */
@Controller
public class ChatController implements ApplicationListener<BrokerAvailabilityEvent> {
    @Autowired
    private SimpMessageSendingOperations sendingOperations;
    private AtomicBoolean brokerAvailable = new AtomicBoolean();
    private Log log= LogFactory.getLog(ChatController.class);
    @MessageMapping("/send")
    public void send(MessageVo messageVo) throws Exception{
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        messageVo.setTime(format.format(new Date()));
        log.debug("messageVo:"+messageVo);

        if(messageVo.getType().equals(MessageVo.PRIVATE)){
            Map<String, Object> map = new HashMap<>();
            messageVo.setContent(messageVo.getContent().substring(messageVo.getContent().indexOf(";")+1));
            map.put(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON);
            sendingOperations.convertAndSendToUser(messageVo.getTo(),"/message/info",messageVo,map);
            sendingOperations.convertAndSendToUser(messageVo.getFrom(),"/message/info",messageVo,map);
        }
        if(messageVo.getType().equals(MessageVo.PUBLICE)){
            System.out.println(brokerAvailable.get());
            if(brokerAvailable.get()) {
                sendingOperations.convertAndSend("/topic/public", messageVo);
            }
        }
    }
    /*
    @Scheduled(fixedDelay=2000)
    public void bocastMessage(){
        MessageVo messageVo=new MessageVo();
        messageVo.setContent("欢迎，现在时间"+new Date().toString());
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        messageVo.setTime(format.format(new Date()));
        messageVo.setType(MessageVo.SYSTEM);
        sendingOperations.convertAndSend("/topic/public", messageVo);
    }*/

    @SubscribeMapping("/welcome")
    public MessageVo enter(Principal principal) throws Exception{
        log.debug(principal);
        MessageVo messageVo=new MessageVo();
        messageVo.setTo(principal.getName());
        messageVo.setContent("欢迎，"+principal.getName()+"进入聊天室，请文明聊天，我们共同进步!!!");
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        messageVo.setTime(format.format(new Date()));
        messageVo.setType(MessageVo.SYSTEM);
        return messageVo;
    }
    @MessageExceptionHandler
    @SendToUser("/message/error")
    public String handleException(Throwable exception) {
        log.warn(exception.getMessage(),exception);
        return exception.getMessage();
    }


    @Override
    public void onApplicationEvent(BrokerAvailabilityEvent brokerAvailabilityEvent) {
        brokerAvailable.set(brokerAvailabilityEvent.isBrokerAvailable());
    }
}
